const axios = require('axios');
const LogUtil = require("./log_util");

let Inc = (new Date()).getTime();
//axios 请求拦截器
axios.interceptors.request.use((config) => {
    // get请求添加一个去缓存变量
    if (config.method === 'get') {
        Inc += 1;
        if (config.params) {
            config.params._ = Inc;
        } else {
            config.params = {
                _: Inc
            };
        }
    }
    return config;
}, (error) => {
    return Promise.reject(error);
});

class HttpUtil {
    static async get(url, params) {
        try {
            return await axios.get(url, {
                params: params,
                headers: {
                    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537',
                    'Accept-Language': 'en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7'
                }
            });
        } catch (error) {
            await LogUtil.logE(`post ${url} error.`);
            throw error;
        }
    }

    static async post(url, data) {
        try {
            return await axios.post(url, data, {
                headers: {
                    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537',
                    'Accept-Language': 'en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7',
                    'Content-Type': 'application/json'
                }
            });
        } catch (error) {
            await LogUtil.logE(`post ${url} error.`);
            throw error;
        }
    }
}

module.exports = HttpUtil;